const { DataTypes, Model } = require('sequelize')
const sequelize = require('../config/database')
const Category = require('./category');

class Article extends Model { }

Article.init({
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    allowNull: false,
    autoIncrement: true,
    comment: '记录ID'
  },
  title: {
    type: DataTypes.STRING,
    allowNull: false,
    comment: '文章标题'
  },
  content: {
    type: DataTypes.TEXT,
    allowNull: false,
    comment: '文章内容'
  },
  author_name: {
    type: DataTypes.STRING,
    allowNull: false,
    comment: '文章作者'
  },
  cover: {
    type: DataTypes.STRING,
    allowNull: true,
    comment: '封面图片'
  },
  categoryId: {
    type: DataTypes.INTEGER,
    allowNull: false,
    comment: '所属分类ID'
  },
  tags: { // 前端传递数组[]
    type: DataTypes.STRING,
    allowNull: false,
    comment: '文章标签',
  },
  short_title: {
    type: DataTypes.STRING,
    allowNull: true,
    comment: '二级标题'
  },
  // 是否置顶 只允许1个置顶
  pinned: {
    comment: '是否置顶',
    type: DataTypes.INTEGER,
    allowNull: false,
    validate: {
      isIn: [[0, 1]] // 限制值为 0: 不置顶、1置顶
    }
  },
  recommended: {
    comment: '是否推荐',
    type: DataTypes.INTEGER,
    allowNull: false,
    validate: {
      isIn: [[0, 1]] // 限制值为 0: 待启用、1:已启用 2:已禁止
    }
  },
  desc: {
    type: DataTypes.TEXT,
    allowNull: false,
    comment: '文章简介'
  },
  stats: {
    comment: '启禁状态',
    type: DataTypes.INTEGER,
    allowNull: false,
    validate: {
      isIn: [[0, 1, 2]] // 限制值为 0: 待启用、1:已启用 2:已禁止
    }
  },
  ctime: {
    comment: "创建时间",
    type: DataTypes.BIGINT,
    allowNull: false,
    defaultValue: () => new Date().getTime()
  },
  mtime: {
    comment: '更新时间',
    type: DataTypes.BIGINT,
    allowNull: false,
    defaultValue: () => new Date().getTime()
  },
}, {
  sequelize,
  modelName: 'Article'
})
Article.belongsTo(Category, { foreignKey: 'categoryId', as: 'category' })

module.exports = Article;